<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Level extends Model
{
    protected $fillable = ['name', 'path', 'pid', 'level'];

    public function getNameAttribute()
    {
        return is_null($this->parent) ? $this->attributes['name'] : $this->parent->name . '|--' . $this->attributes['name'];
    }

    public function parent()
    {
        return $this->belongsTo(self::class, 'pid', 'id');
    }

    public function getPath()
    {
        return is_null($this->parent) ? $this->pid . ',' . $this->id : $this->parent->path . ',' . $this->id;
    }

    public function getLevel()
    {
        return is_null($this->parent) ? 1 : $this->parent->level + 1;
    }

    public static function getChildren($arr, $pid = 0)
    {
        $tree = [];
        foreach ($arr as $key => $v) {
            if ($v['parent_id'] == $pid) {
                $v['children'] = static::getChildren($arr, $v['id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }
}
